package com.wondertek.common.util.security;

import com.wondertek.common.exception.AppException;
import org.springframework.stereotype.Component;

/**
 * @author: gongjiangtao
 * @date: 2024/7/22 11:33
 * @Description: 设置用户信息
 * @Version: 1.0
 */
@SuppressWarnings("all")
@Component("securityUtil")
public class SecurityUtil {

    public static class SecurityContext{

        private static final ThreadLocal<LoginUser> PRINCIPAL = new InheritableThreadLocal<>();

        public static LoginUser get(){return PRINCIPAL.get();}

        public static void setLoginUser(LoginUser principal){
            PRINCIPAL.set(principal);
        }

        public static void remove(){
            PRINCIPAL.remove();
        }
    }

    public static LoginUser getLoginUser(){
        LoginUser principal = SecurityContext.get();
        if(null == principal){
            throw new AppException("user.login.not.found");
        }
        return principal;
    }

    public static LoginUser getDefaultLoginUser(){
        LoginUser loginUser = null;
        try {
            loginUser = getLoginUser();
        }catch (Exception ignored){
        }
        if(loginUser == null){
            loginUser = new LoginUser();
            loginUser.setUserId("N/A");
            loginUser.setUsername("N/A");
        }
        return loginUser;
    }
}
